const buildHtml = require('./index');
const path = require('path');
const { isFile, error, getShellCmd, isDirectory } = require('./utils');

function main(argv) {
	let docxPath = argv['docx-path'];
	let outputPath = argv['output-path'];
	const watch = argv['watch'];
	const cwd = process.cwd();
	if (!docxPath) {
		error('docx-path is null');
		process.exit(0);
	}
	docxPath = path.resolve(cwd, docxPath);

	if (!isFile(docxPath)) {
		error('no such file ' + docxPath);
		process.exit(0);
	}

	if (outputPath) {
		outputPath = path.resolve(cwd, outputPath);

    //如果是个文件夹，则在指定文件夹下生成同名的html
		if (isDirectory(outputPath)) {
      const {name} = path.parse(docxPath);
			outputPath = path.resolve(outputPath,`${name}.html`);
		}
	}

	if (watch && outputPath) {
		getShellCmd('gulp', ['-f', `${path.resolve(__dirname, '../', 'gulpfile.js')}`, 'dev', `--docx-path=${docxPath}`, `--output-path=${outputPath}`], {
			stdio: 'inherit',
			cwd
		});
	} else {
		buildHtml(docxPath, outputPath);
	}

}

module.exports = main;
